// pages/view_order/view_order.js
const db = wx.cloud.database();
const _ = db.command;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        recycleState: ['全部订单', '等待上门', '已完成'],
        goodsState: ['全部', '待付款', '待发货', '已发货', '售后中', '已完成'],
        _titIndex: 1,
        _stateIndex: 0,
        hasOrder: false,
        orderBoxHeight: 0,
        orderList: [],
        orderStateList: [0, 1, 2],
        pageNum: 1,
        pageSize: 6,
        total: 0,
        isLoading: false,   // 节流阀
        isScrollPull: false,
        // 底部弹框
        dialogContent: '已通知卖家优先安排发货',
        isDialogShow: false,
        dialogImg: 'https://s3.bmp.ovh/imgs/2022/06/12/2ae2544f5b3b4fa5.png',
        // 支付框参数
        isPayShow: false,
        price: 0,
        orderParam: {},
        // 商品订单底下功能按钮
        btnText: [[{disabled: true, text: '取消购买'}, {disabled: false, text: '立即支付'}],
            [{disabled: true, text: '申请退款'}, {disabled: false, text: '提醒发货'}],
            [{disabled: true, text: '申请售后'}, {disabled: false, text: '确认完成'}],
            [{disabled: true, text: '联系商家'}, {disabled: false, text: '确认完成'}],
            [],
            [{disabled: true, text: '等待退款'}],
            [/*{disabled: true, text: '删除订单', bgColor: '#F87026'}*/]]
    },
    /**
     * 查看商品详情
     * @param {*} e 
     */
    onToDetail(e) {
        let id = e.currentTarget.dataset.id;
        wx.navigateTo({
          url: '/pages/order_details/order_details?type=' + this.data._titIndex + '&id=' + id,
        });
    },
    /**
     * 点击上方的标题并显示相应内容
     */
    onClickTitle(e) {
        // index: 1-回收订单，2-商品订单
        let index = e.currentTarget.dataset.index;
        let state = [];
        if(index === 1) {
            state = [0, 1, 2];
        }else {
            state = [0, 1, 2, 3, 4];
        }
        this.setData({
            _titIndex: index,
            _stateIndex: 0,
            orderStateList: state
        });
        this.getOrderList(1);
    },
    /**
     * 点击选择状态
     * @param {*} e 
     */
    onClickState(e) {
        let index = e.currentTarget.dataset.index;
        this.setData({
            _stateIndex: index
        });
        this.getOrderStateList();
    },
    /**
     * 改变订单状态列表
     */
    getOrderStateList() {
        let state = [];
        if(this.data._titIndex === 1) {
            if(this.data._stateIndex === 0) {
                state = [0, 1, 2];
            }else if(this.data._stateIndex === 1) {
                state = [0, 1];
            }else {
                state = [2];
            } 
        }else {
            if(this.data._stateIndex === 0) {
                state = [0, 1, 2, 3, 4];
            }else if(this.data._stateIndex === 1) {
                state = [0];
            }else if(this.data._stateIndex === 2) {
                state = [1, 5];
            }else if(this.data._stateIndex === 3) {
                state = [2];
            }else if(this.data._stateIndex === 4) {
                state = [3];
            }else {
                state = [4, 6];
            }
        }
        this.setData({
            orderList: [],
            orderStateList: state
        });
        this.getOrderList(1);
    },
    /**
     * 获取指定回收订单
     * @param {*} state 
     */
    getRecycleOrderList(pageNum) {
        wx.showLoading({
          title: '加载中',
        });
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'getRecycleOrderList',
                reqData: {
                    state: this.data.orderStateList,
                    pageSize: this.data.pageSize,
                    pageNum: pageNum
                }
            }
        }).then(res => {
            // console.log('comRecycleMess success ==>', res);
            if(res.result.resData.data) {
                // 刷新状态
                this.setData({
                    ['orderList[' + (pageNum - 1) + ']']: res.result.resData.data,
                    hasOrder: true,
                    total: res.result.resData.total
                });
            }
        }, err => {
            console.log('comRecycleMess error ==>', err);
        }).finally(() => {
            this.data.isLoading = false;
            wx.hideLoading();
        });
    },
    /**
     * TODO ==> 获取指定商品列表
     * 
     */
    getGoodsOrderList(pageNum) {
        // 暂时未做，将列表值为 0
        wx.showLoading({
            title: '加载中',
        });
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'getIdlemallOrderList',
                reqData: {
                    state: this.data.orderStateList,
                    pageSize: this.data.pageSize,
                    pageNum: pageNum
                }
            }
        }).then(res => {
            // console.log('comRecycleMess success ==>', res);
            if (res.result.resData.data) {
                // 刷新状态
                this.setData({
                    ['orderList[' + (pageNum - 1) + ']']: res.result.resData.data,
                    hasOrder: true,
                    total: res.result.resData.total
                });
            }
        }, err => {
            console.log('comRecycleMess error ==>', err);
        }).finally(() => {
            this.data.isLoading = false;
            wx.hideLoading();
        });
    },
    /**
     * 获取商品列表
     */
    getOrderList(pageNum) {
        if(this.data._titIndex === 1) {
            this.getRecycleOrderList(pageNum);
        }else {
            this.getGoodsOrderList(pageNum);
        }
    },
    /**
     * 获取订单窗口的大小
     */
    getOrderViewSize() {
        this.setData({
            orderBoxHeight: wx.getSystemInfoSync().windowHeight - 105
        });
    },
    /**
     * 点击确认完成
     * @param {*} e
     */
    onComOrder(e) {
        let id = e.currentTarget.dataset.id;
        let pageNum = e.currentTarget.dataset.pagenum;
        let index = e.currentTarget.dataset.index;
        let hIndex = this.data.orderList[pageNum][index].orderForm.ammount;
        let addIntegral = this.getIntegral(hIndex);
        let esPrice = this.data.orderList[pageNum][index].orderForm.estimatedPrice;
        // console.log('data ==>', id, pageNum, index);
        if(this.data._titIndex === 1) {
            wx.cloud.callFunction({
                name: 'databaseApi',
                data: {
                    type: 'comRecycleMess',
                    reqData: id
                }
            }).then(res => {
                // console.log('comRecycleMess success ==>', res, this.data.orderStateList);
                // 刷新状态
                this.setData({
                    hasOrder: false,
                    orderList: [],
                    pageNum: 1
                });
                this.getOrderList(1);
                this.getRecycleOrderList(1);
                return wx.cloud.callFunction({
                    name: 'databaseApi',
                    data: {
                        type: 'updateUserAccount',
                        reqData: {
                            type: ['income', 'recycleProfit', 'integral', 'orderCount'],
                            incNum: [esPrice, esPrice, addIntegral, 1]
                        }
                    }
                });
            }, err => {
                console.log('comRecycleMess error ==>', err);
            }).then(res => {
                // console.log('update account success ==>', res);
            }, err => {
                console.log('update account error ==>', err);
            });
        }
    },
    /**
     * 转到下单页
     */
    onToAddOrder() {
        if(this.data._titIndex === 1) {
            wx.switchTab({
              url: '/pages/recycle/recycle',
            });
        }else {
            wx.navigateTo({
              url: '/subpkg/idlemall/idlemall',
            });
        }
    },
    /**
     * 商品订单的功能按钮
     * @param {*} e 
     */
    onToFunc(e) {
        let type = e.currentTarget.dataset.type;
        let pageNum = e.currentTarget.dataset.page;
        let index = e.currentTarget.dataset.index;
        let orderId = e.currentTarget.dataset.id;
        let goodsName = this.data.orderList[pageNum][index].goodsMess.goodsData.goodsName;
        console.log('func ==>', type, pageNum, index, orderId);
        switch(type) {
            case '取消购买':
                this.cancelBuy(pageNum, index, orderId);
                break;
            case '立即支付':
                this.payOrder(pageNum, index, orderId);
                break;
            case '提醒发货':
                this.remindSend(pageNum, index);
                break;
            case '申请退款':
                this.applyRefund(orderId);
                break;
            case '申请售后':
                this.applyAfterSales(orderId, goodsName);
                break;
            case '确认完成':
                this.confirmCompletion(orderId, goodsName);
                break;
            case '联系商家':
                this.contactSeller(pageNum, index);
                break;
            case '等待退款':
                this.waitForRefund(pageNum, index);
                break;
        }
    },
    /**
     * 取消购买
     * @param {*} index 
     * @param {*} orderId 
     */
    cancelBuy(pageNum, index, orderId) {
        // 显示提示对话框
        wx.showModal({
            title: '提示',
            content: '您确定取消购买了吗？',
            confirmColor: '#55D686',
            cancelColor: '#F87026'
        }).then(res => {
            // console.log('cancel modal success ==>', res);
            if (res.confirm) {
                // 确认取消
                this.cancelBuyFunc(pageNum, index, orderId);
            }
        }, err => {
            console.log('cancel modal error ==>', err);
        });
    },
    /**
     * 确定取消购买
     * @param {*} pageNum 
     * @param {*} index 
     * @param {*} orderId 
     */
    cancelBuyFunc(pageNum, index, orderId) {
        let orderList = this.data.orderList;
        // 将商品数量返回库存
        let amount = orderList[pageNum][index].amount;
        let itemNo = orderList[pageNum][index].itemNo;
        // 取消购买
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'cancelBuy',
                reqData: {
                    itemNo: itemNo,
                    amount: amount,
                    orderId: orderId
                }
            }
        }).then(res => {
            // console.log('cancelBuy success ==>', res);
            this.$showMsg('取消成功');
            this.getOrderStateList();
        }, err => {
            console.log('cancelBuy error ==>', err);
        });
    },
    /**
     * 立即支付
     * @param {*} orderId 
     */
    payOrder(pageNum, index, orderId) {
        let price = this.data.orderList[pageNum][index].payment;
        this.setData({
            isPayShow: true,
            price: price,
            orderParam: {
                "pageNum": pageNum,
                "index": index,
                "orderId": orderId
            } 
        });
        console.log('pageParam ==>', this.data.orderParam);
    },
    /**
     * 支付
     */
    onToPay() {
        let pageNum = this.data.orderParam.pageNum;
        let index = this.data.orderParam.index;
        let orderId = this.data.orderParam.orderId;
        const payBox = this.selectComponent('#pay');
        payBox.closePay();
        wx.showLoading({
          title: '支付中',
        })
        // 订单状态改为：1-待发货，更新支付时间
        db.collection('idlemallOrder').doc(orderId).update({
            data: {
                payTime: new Date().toISOString(),
                orderStatus: 1
            }
        }).then(res => {
            // console.log('pay order success ==>', res);
            wx.hideLoading().then(res => {
                this.$showMsg('支付成功', 'success');
            });
            // 更新列表
            this.getOrderStateList();
        }, err => {
            console.log('pay order error ==>', err);
        }).finally(() => {
            payBox.setData({
                value: '',
                passLength: 0
            });
            this.data.isPayShow = false;
            // 隐藏支付框
            this.setData({
                isPayShow: false
            });
        });
    },
    onCancelPay(e) {
        this.$showMsg('已取消支付');
    },
    /**
     * 申请退款
     * @param {*} orderId 
     */
    applyRefund(orderId) {
        // 订单状态改为：5-退款中
        // 显示提示信息
        wx.showModal({
            title: '提示',
            content: '您确定要申请退款吗？',
            confirmColor: '#55D686',
            cancelColor: '#F87026'
        }).then(res => {
            // console.log('cancel modal success ==>', res);
            if (res.confirm) {
                // 确认取消
                this.goToRefundPage(orderId);
            } else if (res.cancel) {
                this.$showMsg('已取消退款');
            }
        }, err => {
            console.log('cancel modal error ==>', err);
        });
    },
    /**
     * 跳转到退款界面
     * @param {*} orderId 
     */
    goToRefundPage(orderId) {
        wx.navigateTo({
          url: '/subpkg/afterSale/afterSale?id=' + orderId,
        });
    },
    /**
     * 提醒发货
     * @param {*} orderId 
     */
    remindSend(pageNum, index) {
        // 出现安抚弹窗提示，订单实际无改变
        let imgUrl = this.data.orderList[pageNum][index].goodsMess.goodsImg[0];
        this.setData({
            dialogImg: imgUrl,
            isDialogShow: true,
            dialogContent: '已通知卖家优先安排发货'
        });
    },
    /**
     * 等待退款
     * @param {*} pageNum 
     * @param {*} index 
     */
    waitForRefund(pageNum, index) {
        // 出现安抚弹窗提示，订单实际无改变
        let imgUrl = this.data.orderList[pageNum][index].goodsMess.goodsImg[0];
        this.setData({
            dialogImg: imgUrl,
            isDialogShow: true,
            dialogContent: '已通知卖家尽快退款'
        });
    },
    /**
     * 申请售后
     * @param {*} orderId 
     */
    applyAfterSales(orderId, goodsName) {
        // 订单状态改为：3-售后中
        // 显示提示信息
        wx.showModal({
            title: '提示',
            content: '您确定要申请售后吗？',
            confirmColor: '#55D686',
            cancelColor: '#F87026'
        }).then(res => {
            // console.log('cancel modal success ==>', res);
            if (res.confirm) {
                // 确认申请
                this.getAfterSales(orderId, goodsName);
            } else if (res.cancel) {
                this.$showMsg('已取消申请');
            }
        }, err => {
            console.log('cancel modal error ==>', err);
        });
    },
    /**
     * 确认申请售后
     * @param {*} orderId 
     */
    getAfterSales(orderId, goodsName) {
        // 将订单状态改为：3-售后中
        db.collection('idlemallOrder').doc(orderId).update({
            data: {
                orderStatus: 3
            }
        }).then(res => {
            // console.log('after sales success ==>', res);
            this.addGoodsMess(orderId, goodsName, 3);
            this.getOrderStateList();
            this.$showMsg('申请售后成功', 'success');
        }, err => {
            console.log('after sales error ==>', err);
        });
    },
    /**
     * 联系商家
     * @param {*} orderId 
     */
    contactSeller(pageNum, index) {
        // 转到与商家的聊天界面
        let userID = this.data.orderList[pageNum][index].goodsMess.userID;
        const payloadData = {
            conversationID: `C2C${userID}`,
        };
        wx.navigateTo({
            url: `/pages/chat/chat?conversationInfomation=${JSON.stringify(payloadData)}`,
        });
    },
    /**
     * 确认完成
     * @param {*} orderId 
     */
    confirmCompletion(orderId, goodsName) {
        // 订单状态改为：4-已完成
        db.collection('idlemallOrder').doc(orderId).update({
            data: {
                orderStatus: 4
            }
        }).then(res => {
            // console.log('after sales success ==>', res);
            this.addGoodsMess(orderId, goodsName, 4);
            this.getOrderStateList();
            this.$showMsg('已确认完成', 'success');
            return wx.cloud.callFunction({
                        name: 'databaseApi',
                        data: {
                            type: 'updateAccountByIdleOrder',
                            reqData: orderId
                        }
                    });
        }, err => {
            console.log('after sales error ==>', err);
        }).then(res => {
            console.log('update account success ==>', res);
        }, err => {
            console.log('update account error ==>', err);
        });
    },
    /**
     * 添加消息
     * @param {*} orderId 
     * @param {*} goodsName 
     * @param {*} state 
     */
    addGoodsMess(orderId, goodsName, state) {
        // 添加消息
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'addGoodsMess',
                reqData: {
                    orderId: orderId,
                    goodsName: goodsName,
                    state: state
                }
            }
        });
    },
    /**
     * 获取本单积分
     * @param {*} hIndex 
     */
    getIntegral(hIndex) {
        /** 根据所选的预估重量，每单可获得不同的积分
         * [2-6]
         * [4-10]
         * [8-12]
         * [10-15]
         */
        let hList = [
            {region: 4, inc: 2},
            {region: 6, inc: 4},
            {region: 4, inc: 8},
            {region: 5, inc: 10}
        ];
        let integral = Math.floor(Math.random() * hList[hIndex].region) + hList[hIndex].inc;
        return integral;
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options.titId) {
            this.setData({
                _titIndex: JSON.parse(options.titId)
            });
        }
        this.getOrderViewSize();
    },
    /**
     * 监听滚动容器下拉动作
     */
    onScrollPullDownRefresh() {
        this.setData({
            hasOrder: false,
            orderList: [],
            pageNum: 1
        });
        this.getOrderList(1);
        this.setData({
            isScrollPull: false
        });
    },

    /**
     * 监听滚动容器上拉到底部
     */
    onScrollReachBottom() {
        if(!this.data.isLoading && this.data.pageNum * this.data.pageSize < this.data.total) {
            this.data.isLoading = true;
            this.data.pageNum += 1;
            this.getOrderList(this.data.pageNum);
            console.log('down');
        }else {
            this.$showMsg('没有更多订单了');
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getOrderList(1);
        // console.log(this.data.orderStateList)
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    /**
     * 显示提示
     * @param {*} msg 
     * @param {*} type 
     */
    $showMsg(msg, type = 'none') {
        wx.showToast({
          title: msg,
          icon: type
        });
    }
})